<script setup lang="ts">
import { onMounted, ref, nextTick, reactive, h } from "vue";
import { DynamicTable } from "@/components/DynamicTable";
import { PaginationConfig, TableColumn } from "@/components/DynamicTable/types";
import commonSearch from "./commonSearch.vue";
import JsonViewer from "@/components/jsonVewer/index.vue";
import {
  getAssetList,
  deleteAsset,
  deleteTag,
  addTag,
  updateAssetStatus,
} from "../servers";
import { FormItemConfig } from "@/components/DynamicForm/types";
import { ElMessage, ElMessageBox } from "element-plus";
import { StatusTag } from "@/components/DynamicTable/components";

const props = defineProps<{
  task: string;
}>();
const pagination = reactive<PaginationConfig>({
  currentPage: 1,
  pageSize: 10,
  total: 0,
  pageSizes: [10, 20, 50],
  layout: "total, sizes, prev, pager, next",
  background: true,
});

const statusMap = [
  {
    label: "未处理",
    value: 1,
  },
  {
    label: "处理中",
    value: 2,
  },
  {
    label: "忽略",
    value: 3,
  },
  {
    label: "疑似",
    value: 4,
  },
  {
    label: "确认",
    value: 5,
  },
];

const levelMap = [
  {
    label: "严重",
    value: "critical",
  },
  {
    label: "高危",
    value: "high",
  },
  {
    label: "中等",
    value: "medium",
  },
  {
    label: "低危",
    value: "low",
  },
  {
    label: "信息",
    value: "info",
  },
  {
    label: "未知",
    value: "unknown",
  },
];

const assetList = ref([]);
const loading = ref(false);
const dialogVisible = ref(false);
const dialogData = ref<any>({});

// 状态修改相关状态
const statusDialogVisible = ref(false);
const statusForm = ref({
  id: null,
  status: null,
  // remark: "",
});

// 标签编辑相关状态
const editingRowId = ref(null);
const newTagValue = ref("");
const tagInputRef = ref();

const columns = ref<TableColumn[]>([
  {
    label: "url",
    prop: "url",
    show: true,
    width: 120,
  },
  {
    label: "Vulnerability",
    prop: "vulnerability",
    show: true,
    width: 120,
  },
  {
    label: "level",
    prop: "level",
    show: true,
    width: 220,
    render: (row, column, cellValue, index) => {
      return h(StatusTag, {
        status: row.level,
        statusMap: levelMap.reduce(
          (acc, item) => ({
            ...acc,
            [item.value]: {
              text: item.label,
              type:
                item.value === "critical"
                  ? "danger"
                  : item.value === "high"
                  ? "warning"
                  : item.value === "medium"
                  ? "success"
                  : "info",
            },
          }),
          {}
        ),
      });
    },
  },
  {
    label: "mapatched",
    prop: "matched",
    show: true,
    width: 140,
  },
  {
    label: "状态",
    prop: "status",
    show: true,
    render: (row, column, cellValue, index) => {
      return h(StatusTag, {
        status: row.status,
        statusMap: statusMap.reduce(
          (acc, item) => ({
            ...acc,
            [item.value]: {
              text: item.label,
              type:
                item.value === 4 || item.value === 5
                  ? "warning"
                  : item.value === 1
                  ? "success"
                  : "info",
            },
          }),
          {}
        ),
      });
    },
  },
  {
    label: "TAG",
    prop: "tags",
    minWidth: 120,
    show: true,
    slot: "tags",
  },
  {
    label: "时间",
    prop: "time",
    width: 180,
    show: true,
  },
  {
    label: "操作",
    prop: "action",
    width: 220,
    show: true,
    slot: "action",
    fixed: "right",
  },
]);

const formData = ref({
  search: "",
});

// 处理查看详情
const handleViewDetail = (row: any) => {
  console.log("查看详情:", row);

  // 设置详情数据
  dialogData.value = {
    基本信息: {
      URL: row.url,
      漏洞名称: row.vulnerability,
      危险等级:
        levelMap.find((item) => item.value === row.level)?.label || row.level,
      匹配内容: row.matched,
      状态:
        statusMap.find((item) => item.value === row.status)?.label ||
        row.status,
      标签: row.tags?.join(", ") || "无",
      时间: row.time,
    },
    请求信息: row.request || "无",
    响应信息: row.response || "无",
    原始数据: row,
  };

  dialogVisible.value = true;
};

// 处理删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm("确定删除该条数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    await deleteAsset({ ids: [row.id], index: "vul" });
    ElMessage.success("删除成功");
    getPageData();
  });
};

const getPageData = async () => {
  const params: any = {
    ...formData.value,
    pageIndex: pagination.currentPage,
    pageSize: pagination.pageSize,
  };
  if (props.task) {
    params.filter = {
      task: [props.task],
    };
  }
  const { data } = await getAssetList({ data: params, type: "vul" });
  assetList.value = data.list;
  pagination.total = data.total;
};

onMounted(() => {
  getPageData();
});

const handleSearch = (v: any) => {
  // console.log(v, "formData");
  getPageData();
};

const handleSearchReset = () => {
  console.log("reset");
  // 重置表单数据
  formData.value = {
    search: "",
  };
  pagination.currentPage = 1;
  getPageData();
};

// 点击添加标签按钮
const handleAddTag = async (row: any) => {
  console.log("添加标签:", row);
  editingRowId.value = row.id;
  newTagValue.value = "";

  // 等待DOM更新后聚焦输入框
  await nextTick();
  if (tagInputRef.value) {
    tagInputRef.value.focus();
  }
};

// 输入框失去焦点时触发
const handleTagBlur = async (row: any) => {
  const trimmedValue = newTagValue.value.trim();

  if (trimmedValue) {
    // 确保row.tags是数组
    if (!row.tags) {
      row.tags = [];
    }

    // 检查标签是否已存在
    if (!row.tags.includes(trimmedValue)) {
      // row.tags.push(trimmedValue);
      // console.log("添加标签成功:", trimmedValue, "到行:", row);
      try {
        await addTag({ id: row.id, tp: "vul", tag: trimmedValue });
        ElMessage.success("添加标签成功");
        getPageData();
      } catch (error) {
        ElMessage.error("添加标签失败");
      }
    } else {
      console.log("标签已存在:", trimmedValue);
    }
  }

  // 重置编辑状态
  editingRowId.value = null;
  newTagValue.value = "";
};

// 按下回车键时也触发添加
const handleTagKeydown = (event: Event, row: any) => {
  const keyboardEvent = event as KeyboardEvent;
  if (keyboardEvent.key === "Enter") {
    handleTagBlur(row);
  } else if (keyboardEvent.key === "Escape") {
    // 按ESC键取消编辑
    editingRowId.value = null;
    newTagValue.value = "";
  }
};

const handleDeleteTag = async (row: any, tag: string) => {
  console.log("删除标签:", row, tag);
  try {
    await deleteTag({ id: row.id, tp: "vul", tag: tag });
    ElMessage.success("删除标签成功");
    getPageData();
  } catch (error) {
    ElMessage.error("删除标签失败");
  }
};

const handlePaginationChange = (page: number) => {
  pagination.currentPage = page;
  getPageData();
};

const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  pagination.currentPage = 1; // 重置到第一页
  getPageData();
};

// 处理状态修改
const handleUpdateStatus = (row: any) => {
  console.log("修改状态:", row);
  statusForm.value = {
    id: row.id,
    status: row.status,
    // remark: "",
  };
  statusDialogVisible.value = true;
};

// 确认修改状态
const handleConfirmUpdateStatus = async () => {
  try {
    // 这里需要调用更新状态的API
    // 假设API接口名为updateAssetStatus
    await updateAssetStatus({
      id: statusForm.value.id,
      status: statusForm.value.status,
      // remark: statusForm.value.remark,
      tp: "vulnerability",
    });

    ElMessage.success("状态修改成功");
    statusDialogVisible.value = false;
    getPageData();
  } catch (error) {
    ElMessage.error("状态修改失败");
  }
};

// 取消修改状态
const handleCancelUpdateStatus = () => {
  statusDialogVisible.value = false;
  statusForm.value = {
    id: null,
    status: null,
    // remark: "",
  };
};
</script>

<template>
  <commonSearch
    v-model="formData"
    @search="handleSearch"
    @reset="handleSearchReset"
  />
  <div style="height: 10px"></div>
  <el-card>
    <DynamicTable
      :pagination="pagination"
      :columns="columns"
      :data="assetList"
      :loading="loading"
      @current-page-change="handlePaginationChange"
      @size-change="handleSizeChange"
    >
      <template #action="{ row }">
        <el-button type="primary" size="small" @click="handleViewDetail(row)">
          详情
        </el-button>
        <el-button type="danger" size="small" @click="handleDelete(row)">
          删除
        </el-button>
        <el-button type="primary" size="small" @click="handleUpdateStatus(row)">
          修改状态
        </el-button>
      </template>

      <template #tags="{ row }">
        <el-tag
          v-for="tag in row.tags"
          @close="handleDeleteTag(row, tag)"
          closable
          :key="tag"
          type="success"
        >
          {{ tag }}
        </el-tag>

        <!-- 编辑状态：显示输入框 -->
        <el-input
          v-if="editingRowId === row.id"
          ref="tagInputRef"
          v-model="newTagValue"
          size="small"
          placeholder="输入标签名称"
          style="width: 120px; margin-left: 4px"
          @blur="handleTagBlur(row)"
          @keydown="handleTagKeydown($event, row)"
        />

        <!-- 非编辑状态：显示添加按钮 -->
        <el-button
          v-else
          type="default"
          size="small"
          @click="handleAddTag(row)"
          style="margin-left: 4px"
        >
          + addTag
        </el-button>
      </template>
    </DynamicTable>
  </el-card>
  <el-dialog v-model="dialogVisible" title="漏洞详情" width="800px">
    <div class="detail-container">
      <!-- 基本信息 -->
      <div class="detail-section">
        <h3 class="section-title">基本信息</h3>
        <div class="info-grid">
          <div
            class="info-item"
            v-for="(value, key) in dialogData.基本信息"
            :key="key"
          >
            <label class="info-label">{{ key }}:</label>
            <span class="info-value">{{ value }}</span>
          </div>
        </div>
      </div>

      <!-- 请求信息 -->
      <div
        class="detail-section"
        v-if="dialogData.请求信息 && dialogData.请求信息 !== '无'"
      >
        <h3 class="section-title">请求信息</h3>
        <div class="json-container">
          <pre class="code-block">{{ dialogData.请求信息 }}</pre>
        </div>
      </div>

      <!-- 响应信息 -->
      <div
        class="detail-section"
        v-if="dialogData.响应信息 && dialogData.响应信息 !== '无'"
      >
        <h3 class="section-title">响应信息</h3>
        <div class="json-container">
          <pre
            class="code-block"
            v-if="typeof dialogData.响应信息 === 'string'"
            >{{ dialogData.响应信息 }}</pre
          >
          <JsonViewer v-else :data="dialogData.响应信息" />
        </div>
      </div>

      <!-- 完整数据 -->
      <div class="detail-section">
        <h3 class="section-title">完整数据</h3>
        <div class="json-container">
          <JsonViewer :data="dialogData.原始数据" />
        </div>
      </div>
    </div>
  </el-dialog>

  <!-- 状态修改弹窗 -->
  <el-dialog v-model="statusDialogVisible" title="修改状态" width="500px">
    <el-form :model="statusForm" label-width="100px">
      <el-form-item label="当前状态">
        <el-select
          v-model="statusForm.status"
          placeholder="请选择状态"
          style="width: 100%"
        >
          <el-option
            v-for="item in statusMap"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="备注">
        <el-input
          v-model="statusForm.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息（可选）"
        />
      </el-form-item> -->
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleCancelUpdateStatus">取消</el-button>
        <el-button type="primary" @click="handleConfirmUpdateStatus"
          >确定</el-button
        >
      </div>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
// 标签样式
:deep(.el-tag) {
  margin-right: 4px;
  margin-bottom: 2px;
}

// 标签输入框样式
:deep(.el-input.is-small .el-input__inner) {
  height: 24px;
}

// 详情对话框样式
.detail-container {
  max-height: 600px;
  overflow-y: auto;
}

.detail-section {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 2px solid #e4e7ed;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: flex-start;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border-left: 3px solid #409eff;
}

.info-label {
  font-weight: 600;
  color: #606266;
  min-width: 80px;
  margin-right: 8px;
  flex-shrink: 0;
}

.info-value {
  color: #303133;
  word-break: break-word;
  flex: 1;
}

.json-container {
  background: #f8f9fa;
  border-radius: 6px;
  padding: 16px;
  border: 1px solid #e4e7ed;

  :deep(.jv-container) {
    background: transparent;

    .jv-code {
      background: transparent;
      padding: 0;
    }
  }
}

.code-block {
  background: #282c34;
  color: #abb2bf;
  padding: 16px;
  border-radius: 6px;
  font-family: "Courier New", Courier, monospace;
  font-size: 13px;
  line-height: 1.5;
  overflow-x: auto;
  white-space: pre-wrap;
  word-wrap: break-word;
  margin: 0;
}

// 状态修改弹窗样式
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-select) {
  width: 100%;
}

:deep(.el-textarea__inner) {
  resize: vertical;
  min-height: 80px;
}

// 响应式设计
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-label {
    margin-bottom: 4px;
  }
}
</style>
